<template>
  <div></div>
</template>

<script>
import * as THREE from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

export default {
  name: 'TenThree',
  props: {
    msg: String
  },
  mounted() {
    this.initScene();
    this.initCamera();
    this.initRenderer();
    this.addCube();
    this.addAxesHelper();
    this.addOrbitControls();
    this.animation();
  },
  methods: {
    // 初始化场景
    initScene() {
      this.scene = new THREE.Scene();
    },
    // 初始化相机
    initCamera() {
      // 创建一个相机 视点
      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
      // 设置相机的位置
      this.camera.position.x = 2;
      this.camera.position.y = 2;
      this.camera.position.z = 5;
      this.camera.lookAt(0, 0, 0);
    },
    // 初始化渲染器
    initRenderer() {
      // 创建一个渲染器
      this.renderer = new THREE.WebGLRenderer();
      // 设置渲染器尺寸
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(this.renderer.domElement);
    },
    // 添加一个立方体
    addCube() {
      const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
      const cubeMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
      const parentCubeMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

      const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
      let parentCube = new THREE.Mesh(cubeGeometry, parentCubeMaterial);

      // 将子元素添加到父元素里
      parentCube.add(cube);
      parentCube.position.set(-3, 0, 0);
      cube.position.set(3, 0, 0);

      // 设置父元素放大
      // parentCube.scale.set(2,2,2)
      // 设置子元素放大
      // cube.scale.set(2,2,2)

      // 设置父元素旋转
      parentCube.rotation.x = Math.PI / 4;
      // 设置子元素旋转
      cube.rotation.x = Math.PI / 4;

      // 添加父元素到场景里
      this.scene.add(parentCube);
    },
    // 添加世界坐标辅助器
    addAxesHelper() {
      const axesHelper = new THREE.AxesHelper(50);
      this.scene.add(axesHelper);
    },
    // 添加轨道控制器
    addOrbitControls() {
      // this.orbitControls = new OrbitControls(this.camera, this.renderer.domElement);
      this.orbitControls = new OrbitControls(this.camera, document.body);
      // 设置带阻尼的惯性
      this.orbitControls.enableDamping = true;
      // 设置阻尼系数
      this.orbitControls.dampingFactor = 0.05;
      // 设置自动旋转
      // this.orbitControls.autoRotate = true;
    },
    // 动画函数
    animation() {
      // cube.rotation.x += 0.01;
      // cube.rotation.y += 0.01;
      this.orbitControls.update();

      // 渲染
      this.renderer.render(this.scene, this.camera);

      requestAnimationFrame(this.animation);
    }
  }
}
</script>

<style scoped>

</style>
